package com.example.myapplication1.diyview;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class TagLayout  extends ViewGroup {

//    用来保存子view的位置的集合，左上右下
    private List<Rect> rectList = new ArrayList<>();


    public TagLayout(Context context) {
        super(context);

    }


    public TagLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

    }



    public TagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
         int widthUsed = 0;
         int heightUsed = 0;
         int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
         int measureHeight = MeasureSpec.getSize(heightMeasureSpec);


        for (int i =0;i <getChildCount();i++) {

            Rect rect = new Rect();
            rect.left = widthUsed;
            widthUsed += getChildAt(i).getMeasuredWidth();
            measureChildWithMargins(getChildAt(i),widthMeasureSpec,widthUsed,heightMeasureSpec,heightUsed);
            widthUsed += getChildAt(i).getMeasuredWidth();
            rect.right =widthUsed;
            rect.bottom = getChildAt(i).getMeasuredHeight();
            rectList.add(rect);

        }

        setMeasuredDimension(measureWidth,measureHeight);
    }



    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        for(int i=0; i <getChildCount(); i++){

            getChildAt(i).layout(rectList.get(i).left ,rectList.get(i).top, rectList.get(i).right, rectList.get(i).bottom);
        }

    }


    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(),attrs);
    }
}
